/**
 * @Title LoginInActivity.java
 * @Package cn.sinokj.mobile.mall.activity.base
 * @Description TODO(用一句话描述该文件做什么)
 * @author azzbcc Email: azzbcc@sina.com
 * @date 创建时间 2016年5月23日 下午4:36:27
 * @version V1.0
 **/
package cn.sinokj.party.chineseFourParty.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.gyf.barlibrary.ImmersionBar;

import org.json.JSONObject;

import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;
import cn.sinokj.party.chineseFourParty.R;
import cn.sinokj.party.chineseFourParty.activity.base.BaseActivity;
import cn.sinokj.party.chineseFourParty.app.App;
import cn.sinokj.party.chineseFourParty.bean.LoginInfo;
import cn.sinokj.party.chineseFourParty.jpush.utils.JPushUtil;
import cn.sinokj.party.chineseFourParty.service.HttpConstants.ReturnResult;
import cn.sinokj.party.chineseFourParty.service.HttpDataService;
import cn.sinokj.party.chineseFourParty.utils.AppManager;
import cn.sinokj.party.chineseFourParty.utils.Constans;
import cn.sinokj.party.chineseFourParty.utils.Utils;
import cn.sinokj.party.chineseFourParty.utils.code.Base64;
import cn.sinokj.party.chineseFourParty.view.dialog.DialogShow;
import cn.sinokj.party.chineseFourParty.view.dialog.confirm.ConfirmDialog;
import cn.sinokj.party.chineseFourParty.view.dialog.confirm.ConfirmInterface;
import de.greenrobot.event.EventBus;

/**
 * @author azzbcc Email: azzbcc@sina.com
 * @ClassName LoginInActivity
 * @Description 登陆界面
 * @date 创建时间 2016年5月23日 下午4:36:27
 **/
public class LoginInActivity extends BaseActivity {
    private static final int LOGIN = 1;
    private static final int BIND_INFO = 2;
    /*@BindView(R.id.title)
    public TextView titleText;
    @BindView(R.id.topbar_left_img)
    public ImageButton topLeftImage;*/
    @BindView(R.id.login_username)
    public EditText usernameEdit;
    @BindView(R.id.login_password)
    public EditText passwordEdit;
    @BindView(R.id.login_forgot_password)
    public TextView forgotPasswdText;
    private String username, password;
    private String encodeUsername;
    private String encodePassword;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        ButterKnife.bind(this);
        ImmersionBar.with(this).statusBarColor(R.color.white)
                .statusBarDarkFont(true)   //状态栏字体是深色，不写默认为亮色
                .flymeOSStatusBarFontColor(R.color.black).init();
        /*titleText.setText("登录");
        titleText.setVisibility(View.VISIBLE);
        topLeftImage.setVisibility(View.VISIBLE);
        topLeftImage.setBackgroundResource(R.drawable.icon_close);*/
        //forgotPasswdText.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
        SharedPreferences shared = getSharedPreferences("user", Activity.MODE_PRIVATE);
        usernameEdit.setText(shared.getString("username", ""));
        passwordEdit.setText(shared.getString("password", ""));
//		if (initializeArgs()) {
//			new Thread(new LoadDataThread()).start();
//		}
    }

    private void encoded() {
        encodeUsername = Base64.encode(username.getBytes());
        encodePassword = Base64.encode(password.getBytes());
    }

    /*R.id.topbar_left_img,*/
    @OnClick({R.id.login_login, R.id.login_forgot_password, R.id.tourists_login})
    public void onClick(View view) {
        switch (view.getId()) {
         /*   case R.id.topbar_left_img:
                finish();
                break;*/
            case R.id.login_login:
                if (initializeArgs()) {
                    encoded();
                    DialogShow.showRoundProcessDialog(this);
                    new Thread(new LoadDataThread(LOGIN)).start();
                }
                break;
            case R.id.login_forgot_password:
                Intent intent = new Intent();
                intent.setClass(this, ForgotPasswordActivity.class);
                startActivity(intent);
                break;
            case R.id.tourists_login:
                if (getIntent().getBooleanExtra("isTourists", false)) {
                    startActivity(new Intent(LoginInActivity.this, MainActivity.class));
                }
                finish();
                break;
        }
    }

    private boolean initializeArgs() {
        username = usernameEdit.getText().toString().trim();
        if (TextUtils.isEmpty(username)) {
            Toast.makeText(this, "请输入登陆账号", Toast.LENGTH_SHORT).show();
            return false;
        }
        password = passwordEdit.getText().toString().trim();
        if (TextUtils.isEmpty(password)) {
            Toast.makeText(this, "请输入登陆密码", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    @Override
    protected Map<String, JSONObject> getDataFunction(int what, int arg1, int arg2, Object obj) {
        switch (what) {
            case LOGIN:
                return HttpDataService.login(encodeUsername, encodePassword);
            case BIND_INFO:
                return HttpDataService.bindPushInfo(
                        JPushInterface.getRegistrationID(this),
                        JPushUtil.getAppKey(getApplicationContext()),
                        Utils.PLATFORM, Utils.DEVICE_TYPE);
        }
        return super.getDataFunction(what, arg1, arg2, obj);
    }

    @Override
    protected void httpHandlerResultData(Message msg, JSONObject jsonObject) {
        DialogShow.closeDialog();
        switch (msg.what) {
            case LOGIN:
                if (jsonObject.optInt(ReturnResult.NRES) != 1) {
                    Toast.makeText(this, jsonObject.optString(ReturnResult.VCRES), Toast.LENGTH_SHORT).show();
                    return;
                }

                App.loginStatus = true;
                // 存储帐号
                SharedPreferences shared = getSharedPreferences("user", Activity.MODE_PRIVATE);
                SharedPreferences.Editor editor = shared.edit();
                editor.putString("username", username);
                editor.putString("password", password);
                Gson gson = new Gson();
                String s = jsonObject.toString();
                LoginInfo loginInfo = gson.fromJson(s, LoginInfo.class);
                App.nCommitteeId = loginInfo.getnCommitteeId();
                App.loginInfo = loginInfo;
                App.MINE_REFRESH = true;
                editor.commit();

                new Thread(new LoadDataThread(BIND_INFO)).start();
                break;
            case BIND_INFO:
             /*   if (jsonObject.optInt(ReturnResult.NRES) != 1) {
                    Toast.makeText(this, jsonObject.optString(ReturnResult.VCRES), Toast.LENGTH_SHORT).show();
                    return;
                }*/
                //Set<String> tags = new HashSet<String>();
                //tags.add(String.valueOf(jsonObject.optInt("groupId", 0)));
                //mHandler.sendMessage(mHandler.obtainMessage(0, tags));
                finishLogin();
                break;
        }
    }

    private void finishLogin() {
        if (Utils.DEBUG_MODE) {
          /*  Message msg2 = Message.obtain();
            msg2.what = Constans.MINE_REFRESH;
            EventBus.getDefault().post(msg2);*/
            Message msg3 = Message.obtain();
            msg3.what = Constans.HOME_REFRESH;
            EventBus.getDefault().post(msg3);
            Message msg4 = Message.obtain();
            msg4.what = Constans.ANNOUNCEMENT_REFRESH;
            EventBus.getDefault().post(msg4);
            finish();
            return;
        }
        if (Utils.INITIAL_PASSWORD.equals(password)) {
            ConfirmDialog.confirmAction(this, "请及时修改密码!", "确定", null, new ConfirmInterface() {
                @Override
                public void onOkButton() {
                  /*  Message msg2 = Message.obtain();
                    msg2.what = Constans.MINE_REFRESH;
                    EventBus.getDefault().post(msg2);*/
                   /* Message msg3 = Message.obtain();
                    msg3.what = Constans.HOME_REFRESH;
                    EventBus.getDefault().post(msg3);
                    Message msg4 = Message.obtain();
                    msg4.what = Constans.ANNOUNCEMENT_REFRESH;
                    EventBus.getDefault().post(msg4);*/
                    Intent intent = new Intent(LoginInActivity.this, MainActivity.class);
                    startActivity(intent);
                    finish();
                }

                @Override
                public void onCancelButton() {
                }

                @Override
                public void onDismiss(DialogInterface dialog) {

                }
            });
        } else {
           /* Message msg2 = Message.obtain();
            msg2.what = Constans.MINE_REFRESH;
            EventBus.getDefault().post(msg2);*/
           /* Message msg3 = Message.obtain();
            msg3.what = Constans.HOME_REFRESH;
            EventBus.getDefault().post(msg3);
            Message msg4 = Message.obtain();
            msg4.what = Constans.ANNOUNCEMENT_REFRESH;
            EventBus.getDefault().post(msg4);*/
            Intent intent = new Intent(LoginInActivity.this, MainActivity.class);
            startActivity(intent);
            finish();
        }

    }

    @SuppressLint("HandlerLeak")
    private final Handler mHandler = new Handler() {
        @SuppressWarnings("unchecked")
        @Override
        public void handleMessage(Message msg) {
            JPushInterface.setTags(getApplicationContext(), (Set<String>) msg.obj, mTagsCallback);
        }
    };

    private final TagAliasCallback mTagsCallback = new TagAliasCallback() {
        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    logger.i(logs);
                    break;
                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    logger.i(logs);
                    if (JPushUtil.isConnected(getApplicationContext())) {
                        mHandler.sendMessageDelayed(mHandler.obtainMessage(0, tags), 1000 * 60);
                    } else {
                        logger.i("No network");
                    }
                    break;
                default:
                    logs = "Failed with errorCode = " + code;
                    logger.e(logs);
            }
//			JPushUtil.showToast(logs, getApplicationContext());
        }
    };

    @Override
    public void onBackPressed() {
        confirmAction("确定要退出吗？", "确定", "取消", new ConfirmInterface() {
            @Override
            public void onOkButton() {
                AppManager.finishAllActivity();
            }

            @Override
            public void onCancelButton() {

            }

            @Override
            public void onDismiss(DialogInterface dialog) {

            }
        });
    }

    private AlertDialog confirmDialog;

    protected final void confirmAction(String message, String okString, String cancelString,
                                       ConfirmInterface confirmIf) {
        confirmDialog = new AlertDialog.Builder(this, R.style.dialog_round).create();
        confirmDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
                    confirmDialog.dismiss();
                }
                return false;
            }
        });
        final ConfirmInterface confirmInterface = confirmIf;
        confirmDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                if (confirmInterface != null) {
                    confirmInterface.onDismiss(dialog);
                }
            }
        });
        confirmDialog.setCancelable(true);
        confirmDialog.show();
        confirmDialog.setContentView(R.layout.finish_dialog);
        TextView confirm = (TextView) confirmDialog.findViewById(R.id.confirm_message);
        TextView cancel = (TextView) confirmDialog.findViewById(R.id.cancel_bady);
        TextView ok = (TextView) confirmDialog.findViewById(R.id.ok_bady);
        if (!TextUtils.isEmpty(message)) {
            confirm.setText(message);
        }
        if (!TextUtils.isEmpty(okString)) {
            ok.setText(okString);
        } else {
            ok.setVisibility(View.GONE);
        }
        if (!TextUtils.isEmpty(cancelString)) {
            cancel.setText(cancelString);
        } else {
            cancel.setVisibility(View.GONE);
        }

        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (confirmInterface != null) {
                    confirmInterface.onCancelButton();
                }
                confirmDialog.dismiss();
            }
        });
        ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (confirmInterface != null) {
                    confirmInterface.onOkButton();
                }
                confirmDialog.dismiss();
            }
        });
    }
}
